package com.hj.aiagent.app;

import com.hj.aiagent.advisor.LoggerAdvisor;
import com.hj.aiagent.chatmemory.FileBasedChatMemory;
import com.hj.aiagent.rag.LoveAppRagCustomAdvisorFactory;
import com.hj.aiagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

/**
 * @author: hj
 * @description: 娱乐助手APP
 * @date: 2025/7/1 9:41
 */
@Component
@Slf4j
public class RelaxApp {

    private final ChatClient client;

    @Resource
    private VectorStore vectorStore;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    @Resource
    private QueryRewriter queryRewriter;

    @Resource
    private ToolCallback[] toolCallbacks;

    /**
     * ai调用mcp服务
     */
    @Resource
    private ToolCallbackProvider toolCallbackProvider;



    private static final String SYSTEM_PROMPT = "扮演深耕旅游娱乐领域的专家。开场向用户表明身份，告知用户若感到无聊，可倾诉自己的娱乐需求。" +
            "围绕独自休闲、朋友聚会、家庭出游三种场景提问：独自休闲时询问偏好的放松方式及时间安排；" +
            "朋友聚会时询问参与人数及感兴趣的互动类型；家庭出游时询问成员构成及适宜的活动强度。" +
            "引导用户详述所在地区、兴趣偏好、时间预算及特殊需求，以便给出专属的娱乐场所、方式及游戏等攻略推荐。";


    public RelaxApp(ChatModel dashscopeChatModel) {
        //基于内存的记忆
        String filePath = System.getProperty("user.dir") + "/chat_memory";
        FileBasedChatMemory chatMemory = new FileBasedChatMemory(filePath);
        this.client = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(new MessageChatMemoryAdvisor(chatMemory),
                        //自定义日志打印
                        new LoggerAdvisor())
                .build();

    }

    public String doChat(String message, String chatId) {
        ChatResponse chatResponse = client
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String context = chatResponse.getResult().getOutput().getText();
        log.info("context: {}", context);
        return context;
    }

    /**
     * AI 基础对话（支持多轮对话记忆，SSE 流式传输）
     *
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId) {
        return client
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .stream()
                .content();
    }

    record RelaxReport(String title, List<String> suggestions) {
    }

    /**
     * 结构化输出代码
     * @param message 消息
     * @param chatId  聊天 ID
     * @return LoveReport
     */
    public RelaxReport doChatWithReport(String message, String chatId) {
        RelaxReport loveReport = client.prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成旅游娱乐攻略，标题为{用户名}的旅游娱乐攻略，内容为推荐列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(RelaxReport.class);
        log.info("LoveReport: {}", loveReport);
        return loveReport;
    }

    /**
     * 基于向量数据库的查询
     * @param message 消息
     * @param chatId  聊天 ID
     * @return LoveReport
     */
    public String doChatWithRag(String message, String chatId) {
        String rewrite = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = client.prompt()
                .system(SYSTEM_PROMPT)
                .user(rewrite)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new LoggerAdvisor())
                .advisors(new QuestionAnswerAdvisor(vectorStore))
                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(vectorStore, "已婚"))
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("消息：{}", text);
        return text;
    }



    public String doChatWithRagCloud(String message, String chatId) {
        ChatResponse chatResponse = client
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new LoggerAdvisor())
                // 应用增强检索服务（云知识库服务）
                .advisors(loveAppRagCloudAdvisor)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


    /**
     * 使用工具进行聊天
     *
     * @param message 消息
     * @param chatId  聊天 ID
     * @return 字符串
     */
    public String doChatWithTools(String message, String chatId) {
        String rewrite = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = client.prompt()
                .system(SYSTEM_PROMPT)
                .user(rewrite)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new LoggerAdvisor())
//                .advisors(new QuestionAnswerAdvisor(vectorStore))
//                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(vectorStore, "已婚"))
                .tools(toolCallbacks)
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("消息：{}", text);
        return text;
    }

    /**
     * 调用mcp进行聊天
     *
     * @param message 消息
     * @param chatId  聊天 ID
     * @return 字符串
     */
    public String doChatWithMcp(String message, String chatId) {
        String rewrite = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = client.prompt()
                .system(SYSTEM_PROMPT)
                .user(rewrite)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .advisors(new LoggerAdvisor())
//                .advisors(new QuestionAnswerAdvisor(vectorStore))
//                .advisors(LoveAppRagCustomAdvisorFactory.createLoveAppRagCustomAdvisor(vectorStore, "已婚"))
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("消息：{}", text);
        return text;
    }
}
